<?php

namespace backend\modules\plugins\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use backend\models\Extensions;
use backend\models\searchs\Extensions as ExtensionsSearch;

/**
 * Default controller for the `plugins` module
 */
class DefaultController extends Controller
{
    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionIndex()
    {
        if (Yii::$app->request->isPost) {
            $id = Yii::$app->request->post('id');
            $model = Extensions::findOne($id);
            $model->enabled = $model->enabled ? 0 : 1;
            $model->save();
        }
        $searchModel = new ExtensionsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams, ['type' => 'plugin']);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider
        ]);
    }

    /**
     * 编辑插件信息
     * @param int $id 扩展ID
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionEdit($id)
    {
        $model = $this->findModel($id);
        $path = Yii::getAlias('@common/plugins/' . $model->folder . '/' . $model->element . '/' . $model->element . '.xml');
        if (is_file($path)) {
            $xml = simplexml_load_file($path);
            $fields = $xml->config->fields;
        } else {
            $fields = null;
        }
        if (Yii::$app->request->isPost) {
            $model->attributes = Yii::$app->request->post();
            if ($model->save()) {
                $this->redirect(['index']);
            }
        }

        return $this->render('edit', ['model' => $model, 'fields' => $fields]);
    }

    /**
     * Finds the Extensions model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Extensions the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Extensions::findOne(['id' => $id, 'type' => 'plugin'])) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('common', 'REQUESTED_PAGE_NOT_EXIST'));
    }
}
